//
//  ForgetPswNextViewController.m
//  Jingjing
//
//  Created by user on 15/11/9.
//  Copyright © 2015年 Mikeshihua. All rights reserved.
//

#import "ForgetPswNextViewController.h"
#import "LoginViewController.h"
@interface ForgetPswNextViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
@property(nonatomic,strong)UITableView  *forgetPswTab;
@property(nonatomic,strong)NSArray      *placeHolderArr;
@property(nonatomic,strong)UIButton    *confirmChangeBtn;
@end

@implementation ForgetPswNextViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createTheNavigationBar];
    
    if (!_placeHolderArr) {
        _placeHolderArr = @[@"请输入新密码",@"请再次输入密码"];
    }
    [self createUI];
    self.view.backgroundColor = [UIColor hexStringToColor:@"#f3f3f3"];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardShow:)
                                                 name: UIKeyboardDidShowNotification object:nil];
    //注册键盘隐藏通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardHide:)
                                                 name: UIKeyboardDidHideNotification object:nil];
}
#pragma mark -------------创建导航栏及相关控件
-(void)createTheNavigationBar
{
    //    自定义navgationBar
    TopView *topView = [[TopView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 64.0f)];
    [topView setTitile:@"忘记密码"];
    [self.view addSubview:topView];
    
    
    UIButton * backBtn = [[UIButton alloc]initWithFrame:CGRectMake(10.0f, 20.0f, 44.0f, 44.0f)];
    [backBtn setImage:[UIImage imageNamed:@"icon_back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnCLick:) forControlEvents:UIControlEventTouchUpInside];
    backBtn.titleLabel.textAlignment = NSTextAlignmentRight;
    [topView addSubview:backBtn];
}
- (void)backBtnCLick:(UIButton*)btn
{
    [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"" withType:TRUE];
    [self dismissViewControllerAnimated:TRUE completion:^(void){}];
}

-(void)createUI
{

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardhide)];
    tapGesture.cancelsTouchesInView = NO;
    [self.forgetPswTab addGestureRecognizer:tapGesture];
    
    [self.view addSubview:self.forgetPswTab];
    [self.forgetPswTab addSubview:self.confirmChangeBtn];
}
-(UITableView *)forgetPswTab
{
    if (!_forgetPswTab) {
        
        _forgetPswTab = [[UITableView alloc] initWithFrame:CGRectMake(16.0f, 64.0f+16.0f, SCREEN_WIDTH-32.0f, SCREEN_HEIGHT-64.0f-16.0f) style:UITableViewStylePlain];
        _forgetPswTab.delegate = self;
        _forgetPswTab.dataSource = self;
        _forgetPswTab.rowHeight =60.0f;
        _forgetPswTab.backgroundColor = [UIColor clearColor];
        _forgetPswTab.separatorStyle = UITableViewCellSeparatorStyleNone;
        
    }
    return _forgetPswTab;
}

//确认修改按钮
-(UIButton *)confirmChangeBtn
{
    if (!_confirmChangeBtn) {
        _confirmChangeBtn = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH -32.0f)/2-100.0f/2,136.0f, 100.0f, 44.0f)];
        [_confirmChangeBtn addTarget:self action:@selector(confirmChangeBtnTapped) forControlEvents:UIControlEventTouchUpInside];
        [_confirmChangeBtn setTitle:@"确认修改" forState:UIControlStateNormal];
        _confirmChangeBtn.layer.cornerRadius = 5;
        _confirmChangeBtn.layer.masksToBounds = YES;
        _confirmChangeBtn.enabled = NO;
        _confirmChangeBtn.titleLabel.font = [UIFont boldSystemFontOfSize:14.0f];
        [_confirmChangeBtn setBackgroundColor:kColorOrangeNormal forState:UIControlStateNormal];
        [_confirmChangeBtn setBackgroundColor:kColorOrangePressed forState:UIControlStateHighlighted];
        [_confirmChangeBtn setBackgroundColor:kColorOrangeDisabled forState:UIControlStateDisabled];
      

        
    }
    return _confirmChangeBtn;
}

#pragma mark-tableViewDelegate&datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.placeHolderArr.count;
}
static UITextField *__textField;//记录当前的textField
static UITextField *__textFieldPwd;//记录当前的textField
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        
        UIView * separtor = [[UIView alloc]initWithFrame:CGRectMake(0.0f, 59.5f, SCREEN_WIDTH - 32.0f, 0.5)];
        separtor.backgroundColor =  [UIColor hexStringToColor:@"#bdbdbd"];
        separtor.tag = 111;
        [cell.contentView addSubview:separtor];//分割线
       
        UILabel *userlabel = [[UILabel alloc]initWithFrame:CGRectMake(24.0f, 10.0f, 80.0f, 40.0f)];
        userlabel.tag = 1000;
        userlabel.font = [UIFont systemFontOfSize:16.0f];
        userlabel.textColor = kColorTEXT;
        [cell.contentView addSubview:userlabel];
        
        
        UITextField *userTF = [[UITextField alloc] init];
        userTF.tag = 2000;
        userTF.delegate = self;
        userTF.frame = CGRectMake(114.0f, 10.0f, SCREEN_WIDTH - 114.0f- 24.0f, 40.0f);
        userTF.clearButtonMode = UITextFieldViewModeWhileEditing;
        [userTF setValue:[UIFont boldSystemFontOfSize:14.0f] forKeyPath:@"_placeholderLabel.font"];
        userTF.font = [UIFont systemFontOfSize:16.0f];
        userTF.secureTextEntry = YES;
        [cell.contentView addSubview:userTF];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    UILabel *userLabel = (UILabel*)[cell.contentView viewWithTag:1000];
    UITextField *text = (UITextField *)[cell.contentView viewWithTag:2000];
    text.placeholder = [_placeHolderArr objectAtIndex:indexPath.row];
    
    UIView *separtor = (UIView*)[cell.contentView viewWithTag:111];
    
    if (indexPath.row==1) {
        separtor.hidden = YES;
    }else{
        separtor.hidden = NO;
    }

    
    if (indexPath.row==0) {
        
        userLabel.text = @"新密码";
        __textField = text;
    }
    if (indexPath.row==1) {
        userLabel.text = @"确认密码";
        __textFieldPwd = text;
        [text addTarget:self action:@selector(textFieldTapped:) forControlEvents:UIControlEventEditingChanged];
        
        
    }
    
    return cell;
}


- (void)textFieldTapped:(id)sender
{
    if ([AccountTools validatePassWord:__textField.text] && [__textFieldPwd.text isEqualToString:__textField.text]) {
        _confirmChangeBtn.enabled = YES;
        
    }
    else
    {
       _confirmChangeBtn.enabled = NO;
        
        
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)keyboardhide
{
    [__textFieldPwd resignFirstResponder];
    [__textField resignFirstResponder];
}
- (void)confirmChangeBtnTapped
{
    [self.view endEditing:YES];
    
    if ([__textField.text isEqualToString:__textFieldPwd.text]) {
        
        if ([AccountTools validatePassWord:__textFieldPwd.text]==NO) {
            ALERT_VIEW(@"密码必须为8~32位字符")
        }else{
            
            //    执行
            [[AnimationIndicator sharedIndicator] startAnimationWithLoadText:@"加载中..."];
            [AppGlobalClass PostDataWithNSstring:RESTPSWORD withDictionary:@{@"userCd":self.mobile,@"password":__textFieldPwd.text,@"checkCode":self.checkCode} success:^(NSDictionary *dictionary) {
                if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
                {
                    //密码重置成功 去登录界面登录
                    ALERT_VIEW(@"设置成功")
                    [self.presentingViewController.presentingViewController dismissViewControllerAnimated:TRUE completion:^(void){}];
                }else
                {
                    NSString * str = [dictionary objectForKey:@"message"];
                    ALERT_VIEW(str);
                }
                [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"" withType:TRUE];
            } failure:^(NSError *error) {
                [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"" withType:TRUE];
            } networkerror:^(NSString *networkerror) {
                [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"" withType:TRUE];
            }];
        }
        
    }else{
        ALERT_VIEW(@"两次密码输入不一致");
    }
    
    
    
}

-(void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //解除键盘出现通知
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name: UIKeyboardDidShowNotification object:nil];
    //解除键盘隐藏通知
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name: UIKeyboardDidHideNotification object:nil];
}

//键盘下降
- (void)keyboardHide:(NSNotification *)noti
{
    
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:[[noti.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue]];
    [UIView setAnimationCurve:7];
    _forgetPswTab.contentOffset = CGPointMake(0, 0);
    
    [UIView commitAnimations];
}

//键盘升起
- (void)keyboardShow:(NSNotification *)noti
{
    NSValue *value = [noti.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardFrame = [value CGRectValue];
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:[[noti.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue]];
    [UIView setAnimationCurve:7];
    if (keyboardFrame.origin.y != SCREEN_HEIGHT) {
        CGFloat a = _confirmChangeBtn.frame.origin.y+_confirmChangeBtn.frame.size.height+_forgetPswTab.frame.origin.y+80.0f;
        if (a < keyboardFrame.origin.y) {
            _forgetPswTab.contentOffset = CGPointMake(0, 0);
        }else
        {
            _forgetPswTab.contentOffset = CGPointMake(0, 80);
        }
        
    }
    
    [UIView commitAnimations];
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    return YES;
}


@end
